// pages/editDrug/editDrug.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPopup: false,
    dateStr: '',
    date: new Date().getTime(),
    minDate: new Date(2020, 0, 1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}`;
      }
      if (type === 'month') {
        return `${value}`;
      }
      return `${value}`;
    },
    formData: {
      drugName: "",
      ingredient: "",
      indication: "",
      specification: "",
      usageDosage: "",
      place: "",
      expireDate: "",
      surplus: "",
      img: ""
    },
    imgList: [],
    from: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const from = options.from
    console.log("from " + from)
    this.setData({
      from: from
    })

    if (from == "addDrug") {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      this.setData({
        dateStr: `${year}-${month}-${day}`
      });
      let formData = this.data.formData
      formData.expireDate = this.data.dateStr
      this.setData({
        formData: formData
      })
      console.log(this.data.formData)
    } else {
      const id = options.id;
      // 获取药品信息
      const res = await app.call({
        path: '/drug/drugDetail?id=' + id,
        method: 'GET'
      })
      if (res.code === 0) {
        console.log(res.data)
        this.setData({
          formData: res.data.drugDetail
        })
      } else {
        Toast.fail(res.errorMsg);
      }
      if (this.data.formData.img != '') {
        let imgUrl = this.data.formData.img
        let array = imgUrl.split('/');
        let imgName = array[array.length - 1];
        let imgObj = {
          url: imgUrl,
          name: imgName,
        }
        this.data.imgList.push(imgObj)
        this.setData({
          imgList: this.data.imgList
        })
        console.log(this.data.imgList)
      }
      this.setData({
        date: Date.parse(this.data.formData.expireDate),
        dateStr: this.data.formData.expireDate
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },


  onChangeDrugName(event) {
    this.setData({
      'formData.drugName': event.detail,
    });
    console.log(this.data.formData)
  },

  onChangeIngredient(event) {
    this.setData({
      'formData.ingredient': event.detail,
    });
  },

  onChangeIndication(event) {
    this.setData({
      'formData.indication': event.detail,
    });
  },

  onChangeSpecification(event) {
    this.setData({
      'formData.specification': event.detail,
    });
  },

  onChangeUsageDosage(event) {
    this.setData({
      'formData.usageDosage': event.detail,
    });
  },

  onChangePlace(event) {
    this.setData({
      'formData.place': event.detail,
    });
  },

  onChangeSurplus(event) {
    this.setData({
      'formData.surplus': event.detail,
    });
  },

  confirmDate(event) {
    console.log(event)
    const date = new Date(event.detail);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    this.setData({
      date: event.detail,
      dateStr: `${year}-${month}-${day}`
    });
    let formData = this.data.formData
    formData.expireDate = this.data.dateStr
    this.setData({
      formData: formData,
      showPopup: false
    })
    console.log(this.data.formData)
  },

  showDatePicker() {
    this.setData({
      showPopup: true,
    });
  },

  closeDatePicker() {
    this.setData({
      showPopup: false,
    });
  },

  afterRead(event) {
    const file = event.detail.file;
    console.log(file)
    s
    let imgUrl = file.url
    let array = imgUrl.split('/');
    let imgName = array[array.length - 1];
    this.data.imgList.push({
      url: imgUrl,
      name: imgName,
    })
    this.setData({
      imgList: this.data.imgList
    })
    this.compressAndUpload();
  },

  removeImg() {
    this.setData({
      imgList: [],
      'formData.img': ''
    })
  },

  compressAndUpload() {
    let imgUrl = this.data.imgList[0].url
    console.log(imgUrl)
    let array = imgUrl.split('/');
    let imgName = array[array.length - 1];
    const timestamp = new Date().getTime().toString();

    Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: '加载中',
      selector: '#van-toast',
    });
    // 压缩图片
    wx.compressImage({
      src: imgUrl,
      quality: 60,
      success: res => {
        console.log(res.tempFilePath);
        // 将压缩后的图片上传到服务器
        wx.cloud.uploadFile({
          cloudPath: 'drugImg/' + timestamp + imgName,
          filePath: res.tempFilePath,
          config: {
            env: 'prod-1ghizuyv341827b8' // 需要替换成自己的微信云托管环境ID
          },
          success: res => {
            console.log(res.fileID);
            this.setData({
              'formData.img': res.fileID
            })
            Toast.clear();
            Toast.success("上传成功")
          },
          fail: err => {
            Toast.clear();
            Toast.fail("上传失败")
            console.error(err);
          }
        });
      },
      fail: err => {
        console.error(err);
      }
    });
  },

  async onSubmit() {
    if(this.data.formData.drugName==''){
      Toast.fail("药名不能为空");
    }else{
      if (this.data.from == "addDrug") {
        const res = await app.call({
          path: '/drug/addDrug',
          method: 'POST',
          data: this.data.formData
        })
        console.log(res)
        if (res.code === 0) {
          Toast.success("添加成功");
          wx.navigateBack({
            delta: 1
          })
        } else {
          Toast.fail(res.errorMsg);
        }
      } else {
        const res = await app.call({
          path: '/drug/updateDrug',
          method: 'PUT',
          data: this.data.formData
        })
        console.log(res)
        if (res.code === 0) {
          Toast.success("修改成功");
          wx.navigateBack({
            delta: 1
          })
        } else {
          Toast.fail(res.errorMsg);
        }
      }
    }
  },
});